package com.yl.androidutilscenter.utils.ext

import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.ClickUtils

/**
 * @author
 * @description:
 * @date :2024/3/11
 * @version 1.0.0
 */

/**
 * 单个view的点击事件,防止连点，
 * @param duration 默认间隔时长800L 毫秒
 */
@JvmOverloads
fun View.click(duration: Long = 800L, block: () -> Unit) {
    ClickUtils.applySingleDebouncing(this, duration) {
        block.invoke()
    }
}

/**
 * 给多个view设置点击事件,防止连点，
 * @param duration 默认间隔时长800L 毫秒
 */
fun Array<View>.click(duration: Long = 800L, block: () -> Unit) {
    ClickUtils.applySingleDebouncing(this, duration) {
        block.invoke()
    }
}

/**
 * 给TextView的内容设置不同颜色
 * @param msg 内容
 * @param startIndex 开始下标
 * @param endIndex 结束下标
 * @param colorInt 颜色值
 */
fun TextView.setTextWithColor(
    content: String?,
    startIndex: Int,
    endIndex: Int,
    @ColorRes colorInt: Int
) {
    if (content.isNullOrEmpty()) {
        return
    }
    val spannable = SpannableString(content)
    var mStartIndex = startIndex
    var mEndIndex = endIndex
    if (mStartIndex < 0) {
        mStartIndex = 0
    }
    if (mEndIndex < 0 || mEndIndex > content.length) {
        mEndIndex = content.length
    }
    spannable.setSpan(
        ForegroundColorSpan(ContextCompat.getColor(context, colorInt)), mStartIndex, mEndIndex,
        Spannable.SPAN_EXCLUSIVE_INCLUSIVE
    )
    this.text = spannable
}


/**
 * 输入款点击搜索按钮
 */

fun EditText.goToSearch(block: () -> Unit) {
    this.setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            block()
            true
        } else {
            false
        }
    }
}


